<template>
  <div class="simple-seller-edit">
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑商户' : '新增商户'"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="seller-form"
      >
        <el-form-item label="商户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商户名称" />
        </el-form-item>

        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>

        <el-form-item label="分润比例 (%)" prop="profitRatio">
          <el-input-number 
            v-model="form.profitRatio" 
            :min="0" 
            :max="100" 
            :precision="2"
            :step="0.1"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="商户所在地区" prop="region">
          <el-cascader
            v-model="form.region"
            :options="regionOptions"
            placeholder="请选择省/市/区"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="登录手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入登录手机号码" />
        </el-form-item>

        <el-form-item label="登录密码" prop="password">
          <el-input 
            v-model="form.password" 
            type="password" 
            placeholder="请输入登录密码" 
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="form.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码" 
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => null
  }
});

const emit = defineEmits(['update:visible', 'submit', 'cancel']);

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// 是否为编辑模式
const isEdit = computed(() => !!props.editData);

// 表单引用
const formRef = ref(null);

// 表单数据
const form = reactive({
  name: '',
  contactName: '',
  profitRatio: 30, // 默认分润比例
  region: [],
  phone: '',
  password: '',
  confirmPassword: ''
});

// 重置表单 - 确保函数定义在使用之前
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  
  // 重置为初始值
  Object.assign(form, {
    name: '',
    contactName: '',
    profitRatio: 30,
    region: [],
    phone: '',
    password: '',
    confirmPassword: ''
  });
};

// 自定义密码验证规则
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (value.length < 6) {
    callback(new Error('密码长度不能小于6位'));
  } else {
    if (form.confirmPassword !== '') {
      formRef.value.validateField('confirmPassword');
    }
    callback();
  }
};

// 自定义确认密码验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致'));
  } else {
    callback();
  }
};

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入商户名称', trigger: 'blur' }
  ],
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  profitRatio: [
    { required: true, message: '请输入分润比例', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择商户所在地区', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入登录手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
});

// 监听编辑数据变化
watch(
  () => props.editData,
  (newVal) => {
    if (newVal) {
      // 编辑模式，填充表单数据
      Object.keys(form).forEach(key => {
        // 如果是密码字段，编辑时不回显
        if (key !== 'password' && key !== 'confirmPassword') {
          form[key] = newVal[key] !== undefined ? newVal[key] : form[key];
        }
      });
    } else {
      // 新增模式，重置表单
      resetForm();
    }
  },
  { immediate: true, deep: true }
);

// 关闭对话框
const handleClose = () => {
  ElMessageBox.confirm('确认关闭？未保存的数据将会丢失', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      dialogVisible.value = false;
      emit('cancel');
      resetForm();
    })
    .catch(() => {
      // 取消关闭
    });
};

// 提交表单
const submitForm = () => {
  if (!formRef.value) return;
  
  formRef.value.validate((valid) => {
    if (valid) {
      // 处理提交数据，移除确认密码字段
      const submitData = { ...form };
      delete submitData.confirmPassword;
      
      // 将地区数组转换为字符串
      if (submitData.region && submitData.region.length > 0) {
        submitData.regionText = submitData.region.join('/');
      }
      
      emit('submit', submitData);
      ElMessage.success(isEdit.value ? '编辑成功' : '添加成功');
      dialogVisible.value = false;
      resetForm();
    } else {
      ElMessage.error('请填写必填项');
      return false;
    }
  });
};

// 模拟地区数据
const regionOptions = ref([
  {
    value: '北京市',
    label: '北京市',
    children: [
      {
        value: '北京市',
        label: '北京市',
        children: [
          { value: '东城区', label: '东城区' },
          { value: '西城区', label: '西城区' },
          { value: '朝阳区', label: '朝阳区' },
          { value: '海淀区', label: '海淀区' },
          { value: '丰台区', label: '丰台区' }
        ]
      }
    ]
  },
  {
    value: '上海市',
    label: '上海市',
    children: [
      {
        value: '上海市',
        label: '上海市',
        children: [
          { value: '黄浦区', label: '黄浦区' },
          { value: '徐汇区', label: '徐汇区' },
          { value: '长宁区', label: '长宁区' },
          { value: '静安区', label: '静安区' },
          { value: '普陀区', label: '普陀区' }
        ]
      }
    ]
  },
  {
    value: '广东省',
    label: '广东省',
    children: [
      {
        value: '广州市',
        label: '广州市',
        children: [
          { value: '荔湾区', label: '荔湾区' },
          { value: '越秀区', label: '越秀区' },
          { value: '海珠区', label: '海珠区' },
          { value: '天河区', label: '天河区' },
          { value: '白云区', label: '白云区' }
        ]
      },
      {
        value: '深圳市',
        label: '深圳市',
        children: [
          { value: '福田区', label: '福田区' },
          { value: '罗湖区', label: '罗湖区' },
          { value: '南山区', label: '南山区' },
          { value: '宝安区', label: '宝安区' },
          { value: '龙岗区', label: '龙岗区' }
        ]
      }
    ]
  }
]);
</script>

<style scoped lang="scss">
.simple-seller-edit {
  .seller-form {
    max-height: 65vh;
    overflow-y: auto;
    padding: 0 15px;
  }
  
  .dialog-footer {
    text-align: right;
    margin-top: 20px;
  }
}
</style>
